﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using Np.GalleryDownloader.Classes;
using Np.GalleryDownloader.Classes.Extensions;

using MouseKeyboardActivityMonitor.Controls;
using MouseKeyboardActivityMonitor;
using MouseKeyboardActivityMonitor.WinApi;
using HtmlAgilityPack;


namespace Np.GalleryDownloader
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Downloader downloader = new Downloader();
        KeyboardHookListener hk;
        public MainWindow()
        {
            InitializeComponent();

            //hk = new KeyboardHookListener(new GlobalHooker());
            //hk.Enabled = true;
            //hk.KeyDown += hk_KeyDown;

            downloader.Update += downloader_Update;
            downloader.Completed += downloader_Completed;

            txDownloadFolder.Text = downloader.SaveDirectory;


        }

        void downloader_Completed(object sender, EventArgs e)
        {
            lbStatus.Items.Add(string.Format("Download ({0} imgs) finished at {1:g}", lbFetchedImages.Content, DateTime.Now));
        }

        void downloader_Update(Downloader downloaderState)
        {
            var lastDownloadedPage = downloaderState.DownloadPages.Last();
            if (lastDownloadedPage != null)
            {
                int val = lbDownloadedImages.Content.ToString().ToInt();
                lbDownloadedImages.Content = ++val;
                pbDownloadProgress.Value = ++val;
            }
        }

        void hk_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {

        }

        private void TxLink_GotFocus(object sender, RoutedEventArgs e)
        {
            TextBox tb = sender as TextBox;
            tb.SelectAll();
        }
        private void TxLink_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            TextBox tb = sender as TextBox;
            tb.SelectAll();

        }

        private void AddLinkToList(string link)
        {
            downloader.DownloadPages.Add(new DownloadPage(link));
            //grPages.ItemsSource;
        }

        private void AddFolderLinkToList(string p)
        {
            HtmlWeb web = new HtmlWeb();
            HtmlDocument doc = web.Load(p);

            var allLinksNodes = doc.DocumentNode.SelectNodes(@"//a[@href]");
            if (allLinksNodes != null)
            {
                foreach (var lnk in allLinksNodes.Select(a => a.Attributes["href"].Value))
                {
                    var attr = lnk;
                    var contains = (from dp in downloader.DownloadPages
                                    where dp.Link.ToLower().Equals(lnk.ToLower())
                                    select dp).FirstOrDefault();
                    bool status = false;
                    if (contains == null)
                        downloader.DownloadPages.Add(new DownloadPage(lnk));
                }

            }

        }

        private void BtDownload_Click(object sender, RoutedEventArgs e)
        {
            // TODO handle download
            pbDownloadProgress.Minimum = 0;
            pbDownloadProgress.Maximum = lbFetchedImages.Content.ToString().ToInt();
            pbDownloadProgress.Value = 0;

            try
            {
                DirectoryInfo di = new DirectoryInfo(txDownloadFolder.Text);
                if (!di.Exists)
                    di.Create();
            }
            catch { }

            lbStatus.Items.Add(string.Format("Starting download at {0:g}", DateTime.Now));
            downloader.DownloadAsync();
        }

        private void btClear_Click(object sender, RoutedEventArgs e)
        {
            this.downloader.DownloadPages.Clear();
            this.UpdateStatus();
            this.pbDownloadProgress.Value = 0;
            this.lbDownloadedImages.Content = 0;
            txLink.Text = string.Empty;
            txLink.Focus();
        }

        private void btChooseDirectory_Click(object sender, RoutedEventArgs e)
        {
            var diag = new System.Windows.Forms.FolderBrowserDialog();
            diag.RootFolder = Environment.SpecialFolder.MyComputer;
            diag.ShowNewFolderButton = true;
            diag.Description = "Select your download directory";
            diag.SelectedPath = downloader.SaveDirectory;

            System.Windows.Forms.DialogResult dr = diag.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                downloader.SaveDirectory = diag.SelectedPath;
                txDownloadFolder.Text = downloader.SaveDirectory;
            }
        }

        protected void UpdateStatus()
        {
            lbFetchedPages.Content = downloader.DownloadPages.Count;
            lbFetchedImages.Content = (from d in downloader.DownloadPages
                                       select d.ImageLinks.Count()).Sum();
        }

        private void txLink_TextChanged(object sender, TextChangedEventArgs e)
        {
            var tb = sender as TextBox;
            TryAddLinkFromTextBox();
        }



        private void TryAddLinkFromTextBox()
        {
            if (!string.IsNullOrEmpty(txLink.Text))
            {
                var contains = (from dp in downloader.DownloadPages
                                where dp.Link.ToLower().Equals(txLink.Text.ToLower())
                                select dp).FirstOrDefault();
                bool status = false;
                if (contains == null)
                    AddLinkToList(txLink.Text);
                this.UpdateStatus();
                txLink.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                txLink.Focus();
            }
        }

        private void AddPagesFromTextBox()
        {
            if (!string.IsNullOrEmpty(txFolderPage.Text))
            {
                AddFolderLinkToList(txFolderPage.Text);
                this.UpdateStatus();
                txFolderPage.MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
                txFolderPage.Focus();
            }
        }

        private void Window_Drop_1(object sender, DragEventArgs e)
        {
            Console.Write(e.Data);
        }

        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {
            txLink.Focus();
        }

        private void btAddFolder_Click(object sender, RoutedEventArgs e)
        {
            AddPagesFromTextBox();
        }



    }
}
